
#include "Serial.h"

Serial::Serial(const char* port, int baud)
{
  struct termios toptions;
  
  ROS_INFO("init_serialport: opening port %s @ %d bps\n", port ,baud);

  fd = open(port, O_RDWR | O_NOCTTY);// | O_NDELAY);
  if (fd == -1)  {
    ROS_ERROR("init_serialport: Unable to open port ");
  }
  
  if (tcgetattr(fd, &toptions) < 0) {
    ROS_ERROR("init_serialport: Couldn't get term attributes");
  }
  speed_t brate = baud; // let you override switch below if needed
  
  switch(baud) {
  case 4800:   brate=B4800;   break;
  case 9600:   brate=B9600;   break;
#ifdef B14400
  case 14400:  brate=B14400;  break;
#endif
  case 19200:  brate=B19200;  break;
#ifdef B28800
  case 28800:  brate=B28800;  break;
#endif
  case 38400:  brate=B38400;  break;
  case 57600:  brate=B57600;  break;
  case 115200: brate=B115200; break;
  }
  cfsetispeed(&toptions, brate);
  cfsetospeed(&toptions, brate);
  
  // 8N1
  toptions.c_cflag &= ~PARENB;
  toptions.c_cflag &= ~CSTOPB;
  toptions.c_cflag &= ~CSIZE;
  toptions.c_cflag |= CS8;
  // no flow control
  toptions.c_cflag &= ~CRTSCTS;
  
  toptions.c_cflag |= CREAD | CLOCAL;  // turn on READ & ignore ctrl lines
  toptions.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl
  
  toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
  toptions.c_oflag &= ~OPOST; // make raw
  
  // see: http://unixwiz.net/techtips/termios-vmin-vtime.html
  toptions.c_cc[VMIN]  = 0;
  toptions.c_cc[VTIME] = 20;
  
  if( tcsetattr(fd, TCSANOW, &toptions) < 0) {
    ROS_ERROR("init_serialport: Couldn't set term attributes");
  }

  // Assign write system call to class call
  Write = boost::bind(write, fd, _1, _2);
}

Serial::~Serial(){  close(fd); }

//int Serial::Read_until(
